package com.xigua.xcar.constant;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;

public class CommonUtil {
	// 错误异常
	public static final String ERROR_NO_INPUT_CONTEXT = "please input param context";

	// 中国大陆三大运营商imei
	public static final String CHA_IMSI = "46003";
	public static final String CMCC_IMSI_1 = "46000";
	public static final String CMCC_IMSI_2 = "46002";
	public static final String CHU_IMSI = "46001";

	// 中国大陆三大运营商 provider
	public static final int CMCC = 0;
	public static final int CHU = 1;
	public static final int CHA = 2;
	public static final int NOPROVIDER = 999;
	
	public final static int NONET = 0;
	public final static int CMNET = 1;
	public final static int CMWAP = 2;
	public final static int WIFI = 3;

	// 获取客户端信息

	public static ClientInfo getClientInfo(Context context) {
		if (context == null) {
			throw new IllegalStateException(ERROR_NO_INPUT_CONTEXT);
		}

		String hsman = android.os.Build.MANUFACTURER;// 手机厂商
		String hstype = android.os.Build.MODEL;// 手机型号
		String hssdk = android.os.Build.VERSION.SDK;// 手机SDK版本
		int width = 0;// 手机屏幕宽
		int height = 0;// 手机屏幕高
		int dpi = 0;	//手机的dpi
		if (context instanceof Activity) {
			DisplayMetrics dm = new DisplayMetrics();
			((Activity) context).getWindowManager().getDefaultDisplay()
					.getMetrics(dm);
			width = dm.widthPixels;
			height = dm.heightPixels;
			dpi = dm.densityDpi;
		} else {
			width = 0;
			height = 0;
			dpi = 0;
		}
		int ram = getTotalMemory();// 手机总内存 //单位MB
		int touch = 1; // 是否触屏手机//都是触摸屏
		String imei = getImei(context); // 手机标识
		String imsi = getImsi(context);
		int provider = getProvider(imsi);

		ClientInfo clientInfo = new ClientInfo();
		clientInfo.setHsman(hsman);
		clientInfo.setHstype(hstype);
		clientInfo.setWidth(width);
		clientInfo.setHeight(height);
		clientInfo.setDpi(dpi);
		clientInfo.setImei(imei);
		clientInfo.setImsi(imsi);
		clientInfo.setRam(ram);
		clientInfo.setTouch(touch);
		clientInfo.setProvider(provider);
		clientInfo.setVersionCode(convertVirsion(hssdk));
		clientInfo.setPlatformVer(getVersionName(context));

		return clientInfo;
	}

	public static String getVersionName(Context context) {
		String versionName = "";
		try {
			versionName = context.getPackageManager().getPackageInfo(
					context.getPackageName(), 0).versionName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return versionName;

	}

	public static int getVersionCode(Context context) {
		int versionCode = 0;
		try {
			versionCode = context.getPackageManager().getPackageInfo(
					context.getPackageName(), 0).versionCode;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return versionCode;
	}

	private static String convertVirsion(String version) {

		String sdk = null;
		sdk = version;
		if (version.equals("4")) {
			sdk = "1.6";
		} else if (version.equals("7")) {
			sdk = "2.1";

		} else if (version.equals("8")) {
			sdk = "2.2";
		} else if (version.equals("9") || version.equals("10")) {
			sdk = "2.3";
		} else if (version.equals("11") || version.equals("12")
				|| version.equals("13")) {
			sdk = "3.0";
		} else if (version.equals("14") || version.equals("15")) {
			sdk = "4.0";
		}

		return sdk;
	}

	// 获取手机总内存
	public static int getTotalMemory() {
		String str1 = "/proc/meminfo";
		String str2;
		String[] arrayOfString;
		int initial_memory = 0;
		try {
			FileReader localFileReader = new FileReader(str1);
			BufferedReader localBufferedReader = new BufferedReader(
					localFileReader, 8192);
			str2 = localBufferedReader.readLine();
			arrayOfString = str2.split("\\s+");
			for (String num : arrayOfString) {
				Log.i(str2, num + "\t");
			}
			initial_memory = Integer.valueOf(arrayOfString[1]).intValue();// KB
			localBufferedReader.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return initial_memory / 1024; // MB
	}

	// 获取当前网络状态
	public static int getAPNType(Context context) {
		int netType = NONET;
		ConnectivityManager connMgr = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
		if (networkInfo == null) {
			return netType;
		}
		int nType = networkInfo.getType();
		if (nType == ConnectivityManager.TYPE_MOBILE) {
			if (networkInfo.getExtraInfo().toLowerCase().equals("cmnet")) {
				netType = CMNET;
			} else {
				netType = CMWAP;
			}
		} else if (nType == ConnectivityManager.TYPE_WIFI) {
			netType = WIFI;
		} else{
			boolean b = ConnectivityManager.isNetworkTypeValid(nType);
			if(b){
				netType = WIFI;
			}
		}
		
		return netType;
	}

	private static final String IMEI_NONE = "000000F1F000000";

	// 获取手机IMEI号
	public static String getImei(Context context) {
		if (context == null) {
			return IMEI_NONE;
		}
		TelephonyManager phoneManager = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		if (phoneManager == null) {
			return IMEI_NONE;
		}
		String imei = phoneManager.getDeviceId();
		if (imei == null) {
			return IMEI_NONE;
		}
		return imei;
	}

	private static String mIMSI = null;
	private static final String IMSI_NONE = "dd";

	// 获取SIM卡IMSI号
	public static String getImsi(Context context) {
		if (null != mIMSI) {
			return mIMSI;
		}
		Random mRandom = new Random();

		if (context == null) {
			mIMSI = IMSI_NONE + mRandom.nextInt();
			return mIMSI;
		}
		TelephonyManager phoneManager = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		if (phoneManager == null) {
			mIMSI = IMSI_NONE + mRandom.nextInt();
			return mIMSI;
		}
		mIMSI = phoneManager.getSubscriberId(); // sim卡标识
		if (mIMSI == null) {
			mIMSI = IMSI_NONE + mRandom.nextInt();
			return mIMSI;
		}
		return mIMSI;
	}

	// 获取IMSI号的供应商
	public static int getProvider(String imsi) {
		int provider = NOPROVIDER; // 当前sim卡运营商 //3为未知的 或者没有sim卡的比如平板
		if (imsi != null) {
			if (imsi.startsWith(CMCC_IMSI_1) || imsi.startsWith(CMCC_IMSI_2)) {// 中国移动
				provider = CMCC;
			}
			else if (imsi.startsWith(CHU_IMSI)) {// 中国联通
				provider = CHU;
			}
			else if (imsi.startsWith(CHA_IMSI)) {// 中国电信
				provider = CHA;
			}
		}
		return provider;
	}

	// 启动系统设置界面
	public static void launchSystemNetworkSetting(Context context) {
		Intent intent = new Intent();
		Context contxt;
		try {
			contxt = context.createPackageContext("com.android.settings",
					Context.CONTEXT_IGNORE_SECURITY);
			intent.setClassName(contxt, "com.android.settings.WirelessSettings");
			context.startActivity(intent);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
	}

	public static boolean isLandScape(Context context) {
		boolean island = false;
		int width = 0;// 手机屏幕宽
		int height = 0;// 手机屏幕高
		if (context instanceof Activity) {
			DisplayMetrics dm = new DisplayMetrics();
			((Activity) context).getWindowManager().getDefaultDisplay()
					.getMetrics(dm);
			width = dm.widthPixels;
			height = dm.heightPixels;
			if (width > height) {
				island = true;
			} else {
				island = false;
			}
		}
		return island;
	}

	private static String CCID = null;
	
	
	public static boolean isNeedKeepService(Context context){
	    boolean isKeepService = true;
	   getCCID(context);
	   if(CCID!=null){
	       if(CCID.startsWith("1_")){
	           isKeepService = false;
	       }else{
	           isKeepService = true;
	       }
	   }
	   return isKeepService;
	}

 public static String getCCID(Context context) {
     if (CCID != null && !"".equals(CCID)) {
      return CCID;
     }
     String text=null;
     try {  
         text = getChannelId(context);
         if(text==null){
             InputStream is = context.getAssets().open("skymobi_a");
             int size = is.available();
             byte[] buffer = new byte[size];
             is.read(buffer);
             is.close();
             text = new String(buffer, "UTF-8");
             Pattern p = Pattern.compile("\\s*|\t|\r|\n");
             Matcher m = p.matcher(text);
             text = m.replaceAll("");
         }
         CCID=text;
      return CCID;
     } catch (Exception e) {
      e.printStackTrace();
      return null;
     }
    }
 
	
 	public static String getChannelId (Context context) throws Exception {
     InputStream is = null;
     is = context.getAssets().open("skymobi_a");
     if (is.available() != 0) {
          byte[] asset = new byte[is.available()];
          is.read(asset);
          String skymobi_a_str = new String(asset);
          if (!skymobi_a_str.contains("_"))
               return null;
          String skymobi_a_type = skymobi_a_str.subSequence(0,
                   skymobi_a_str.indexOf("_")).toString();
          if (skymobi_a_type.equals("1")) {
               String skymobi_a = getSkyMobiA();
               if (null == skymobi_a) {
                   return null;
               }
               String mobi_project = getSkyMobiProject();
               String channelNum = "1_" + skymobi_a
                   + (mobi_project == null ? "" : mobi_project);
                return channelNum;  

          }
     }
     return null;
 }

 	public static String getSkyMobiA() {
	     try {
	          Field field = Build.class.getField("SKYMOBI_A");
	          String skyMobiA = (String) field.get(null);
	          return skyMobiA;
	     } catch (Exception e) {
	          return null;
	     }
 	}

 	public static String getSkyMobiProject() {
	    try {
	         Field field = Build.class.getField("SKYMOBI_PROJECT");
	         String skyMobiProject = (String) field.get(null);
	         return skyMobiProject;
	    } catch (Exception e) {
	         return null;
	    }
 	}

}
